package com.heima.user.services.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.services.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
            //检查手机号密码
        String phone = dto.getPhone();
        String password = dto.getPassword();
        if(StringUtils.isNotBlank(phone)&&StringUtils.isNotBlank(password)){
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPassword, dto.getPhone()));
            if (apUser!=null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            String inputPwd = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
            if (!inputPwd.equals(apUser.getPassword())) {
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            if (apUser.getStatus().intValue()!=0) {
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            HashMap map = new HashMap();
            map.put("token",token);
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("user",apUser);
            ResponseResult.okResult(map);
        }else {
            if (dto.getEquipmentId()==null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"未发现设备id");
            }
            String token = AppJwtUtil.getToken(Long.valueOf(0L));
            HashMap map = new HashMap();
            map.put("token",token);
            ResponseResult.okResult(map);


        }


        return null;
    }
}
